package GoFile

import (
	"fmt"
	"github.com/garyburd/redigo/redis"
	"github.com/spf13/viper"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"m/Global"
	"m/model"
	"os"
)



func InitDB(v *viper.Viper) (db *gorm.DB, erre error){
	var err error
	//driverName := viper.GetString("datasource.driverName")
	//host := viper.GetString("datasource.host")
	//port := viper.GetString("datasource.port")
	//database := viper.GetString("datasource.database")
	//username := viper.GetString("datasource.username")
	//password := viper.GetString("datasource.password")
	//charset := viper.GetString("datasource.charset")

	args := fmt.Sprintf("user=%s password=%s dbname=%s host=%s port=%s sslmode=disable TimeZone=Asia/Shanghai",
		v.GetString("datasource.username"),
		v.GetString("datasource.password"),
		v.GetString("datasource.database"),
		v.GetString("datasource.host"),
		v.GetString("datasource.port"),
	)
	db, err = gorm.Open(postgres.Open(args), &gorm.Config{})
	if err != nil {
		panic("连接数据库失败" + err.Error())
		return db, erre
	}
	fmt.Println("数据库连接成功！")
	err = db.AutoMigrate(&model.Student{})
	if err != nil {
		return nil, err
	}
	return db, erre
}

func InitRedisDB(v *viper.Viper) (conn redis.Conn, err error)  {
	db, err := redis.Dial("tcp", v.GetString("redis.host") + ":" + v.GetString("redis.port"))
	if err != nil {
		fmt.Println("连接redis失败！, ", err.Error())
		Global.Flag = false
		return
	}
	Global.Flag = true
	return db, err
}

func InitConfig() (v *viper.Viper){
	workDir, _:=os.Getwd()
	v = viper.New()
	v.SetConfigName("application")
	v.SetConfigType("yml")
	v.AddConfigPath(workDir + "/config")
	err := v.ReadInConfig()
	if err != nil {
		fmt.Printf("读取配置文件出错:%s\n", err)
	}
	return v
}
